<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="平台" prop="pIds">
        <el-select v-model="queryParams.pIds" placeholder="请选择平台" clearable style="width: 200px;">
          <el-option v-for="platform in platformList" :key="platform.id" :label="platform.name" :value="platform.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="账号名" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入账号名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="过期时间" style="width: 308px">
        <el-date-picker v-model="daterangeExceedTime" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 100px;" clearable>
          <el-option v-for="dict in number_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="父账号" prop="status">
        <el-select v-model="queryParams.pId" placeholder="请选择父亲账号" style="width: 200px;" clearable>
          <el-option v-for="p in parentList" :key="p.id" :label="p.desc" :value="p.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['app:child:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['app:child:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['app:child:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['app:child:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="() => { getParentList(), getList() }"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="childList" @selection-change="handleSelectionChange" style="width: 120%;"
      @sort-change="handleSortChange" :default-sort="{ prop: 'createTime', order: 'descending' }">
      <el-table-column fixed type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" width="50" />
      <el-table-column label="备注" align="center" prop="desc" width="150" />
      <el-table-column label="账号" align="center" prop="username" width="120" />
      <el-table-column label="密码" align="center" prop="password" width="120" />
      <el-table-column sortable="custom" label="过期时间" align="center" prop="exceedTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.exceedTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <dict-tag :options="number_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="父账备注" align="center" prop="pId" width="180">
        <template #default="{ row }">
          <span>{{ handleQueryParent(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成功登录次数" align="center" prop="sucCount" width="150">
        <template #default="scope">
          <el-tag type="warning">{{ scope.row.sucCount }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="失败登录次数" align="center" prop="failCount" width="150">
        <template #default="scope">
          <el-tag type="danger">{{ scope.row.failCount }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="mac地址" align="center" prop="mac" width="180" />
      <el-table-column label="城市" align="center" prop="addr" width="210" />
      <el-table-column label="ip" align="center" prop="ip" width="150" />
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="380">
        <template #default="scope">
          <el-button link type="success" icon="View" @click="touterToLog(scope.row.id)"
            v-hasPermi="['app:childLog:list']">日志</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['app:child:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['app:child:remove']">删除</el-button>
          <el-button v-hasPermi="['app:child:edit']" link type="danger" icon="RefreshRight"
            @click="resetAddrInfo(scope.row)">重置地址信息</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page-sizes="[100, 200, 300, 500, 1000]"
      v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改子账号管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="childRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="账号名" prop="username">
          <el-input v-model="form.username" placeholder="请输入账号名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="父账号" prop="pId">
          <el-select v-model="form.pId" placeholder="请选择父亲账号">
            <el-option v-for="item in parentFilter()" :key="item.id" :label="item.username" :value="item.id">
              {{ item.username }} {{ item.desc }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="过期时间" prop="exceedTime">
          <el-date-picker clearable v-model="form.exceedTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择过期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="form.desc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" class="ml-2" :active-value="'1'" :inactive-value="'0'"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Child">
import { listChild, getChild, delChild, addChild, updateChild } from "@/api/app/child";
import { listParent } from "@/api/app/parent";
import { listPlatform } from "@/api/app/platform";
const { proxy } = getCurrentInstance();
const { number_status } = proxy.useDict('number_status');

const childList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeExceedTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 100,
    username: null,
    pId: null,
    createTime: null,
    desc: null,
    status: null,
    pIds: null,
    orderByColumn: 'createTime',
    isAsc: 'descending'
  },
  rules: {
    username: [
      { required: true, message: "账号名不能为空", trigger: "blur" }
    ],
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" }
    ],
    pId: [
      { required: true, message: "父亲账号id不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询子账号管理列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeExceedTime && '' != daterangeExceedTime) {
    queryParams.value.params["beginExceedTime"] = daterangeExceedTime.value[0];
    queryParams.value.params["endExceedTime"] = daterangeExceedTime.value[1];
  }
  const p = JSON.parse(JSON.stringify(queryParams.value));
  if (p.pIds != null) {
    p.pIds = selectPlatform(p.pIds)
    if (p.pIds.length == 0) {
      childList.value = []
      loading.value = false;
      return
    }
  }
  listChild(p).then(response => {
    childList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: undefined,
    username: null,
    password: null,
    pId: null,
    exceedTime: null,
    desc: '',
    status: '1'
  };
  proxy.resetForm("childRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}



// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加子账号管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getChild(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改子账号管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["childRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateChild(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addChild(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除子账号编号为"' + _ids + '"的数据项？').then(function () {
    return delChild(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/child/export', {
    ...queryParams.value
  }, `child_${new Date().getTime()}.xlsx`)
}



// -------------------------------------父账 管理 -----------------------------
const parentList = ref([]);
// 获取 父账号列表
function getParentList() {
  listParent({
    pageNum: 1,
    pageSize: 10000,
  }).then((data) => {
    parentList.value = data.rows;
  })
}

/**
 * 过滤父亲账号
 * @param ps 
 */
function parentFilter(){
  let ps = parentList.value
  return ps.filter(p => p.platformId === queryParams.value.pIds)
}
getParentList()

// --------------------------  平台列表 ----------------------------
const platformList = ref([])
function getPlatformList() {
  listPlatform({
    pageNum: 1,
    pageSize: 10000
  }).then(data => {
    platformList.value = data.rows
  })
}

function selectPlatform(id) {
  let ids = []
  parentList.value.forEach((p) => {
    if (p.platformId === id) {
      ids.push(p.id)
    }
  })
  // queryParams.value.pIds = ids
  return ids
}
getPlatformList()

// 查询 父 账号信息
function handleQueryParent(row) {
  const info = parentList.value.find(item => item.id === row.pId)
  if (info === undefined) return "无"
  return info.desc + " " + info.username
}

/**
 * 重置地址信息
 */
function resetAddrInfo(row) {
  const from = {
    ...row
  }
  proxy.$modal.confirm('是否确认重置子账号编号为"' + row.id + '"的地址信息？').then(function () {
    from.ip = from.addr = from.mac = ""
    return updateChild(from);
  }).then(() => {
    proxy.$modal.msgSuccess("修改成功");
    getList();
  }).catch(() => { });

}
function handleSortChange(sort) {
  queryParams.value.orderByColumn = sort.prop;
  queryParams.value.isAsc = sort.order
  getList();
}
// ----------------------------------  查看 日志 -----------------
import { useRouter } from "vue-router";
const router = useRouter();
// 路由到 日志 界面
function touterToLog(id) {
  router.push({
    query: {
      id
    },
    name: "ChildLog"
  })
}

getList();

/** 重置按钮操作 */
function resetQuery() {
  daterangeExceedTime.value = [];
  proxy.resetForm("queryRef");
  getParentList()
  getPlatformList()
  handleQuery();
}
</script>
<style scoped>
.el-table :deep(.el-table__header) {
  user-select: none;
}
</style>
